package com.ellecity06.cwhiskymall

import android.app.Application
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import cn.jpush.android.api.JPushInterface
import com.ellecity06.common.helper.LoginHelper
import com.ellecity06.common.utils.netAvailable
import com.ellecity06.cwhiskymall.constant.BusConstants
import com.ellecity06.cwhiskymall.constant.Constants
import com.ellecity06.cwhiskymall.exception.GlobalExceptionHandler
import com.ellecity06.cwhiskymall.helper.JPushHelper
import com.ellecity06.cwhiskymall.http.ServerConfig
import com.ellecity06.cwhiskymall.storage.AppStorage
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.login.LoginActivity
import com.ellecity06.cwhiskymall.utils.LogUtils
import com.hjq.toast.Toaster
import com.jeremyliao.liveeventbus.LiveEventBus
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.QbSdk

/**
 * @author ellecity06
 * @time 2023/3/29 16:27
 * @des
 */
//@HiltAndroidApp
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        appContext = this
        LoginHelper.instance.initialize(LoginActivity::class.java, ::onLogout)
        DebugManager.initSdk(this)

        if (AppStorage.agreement) {
            initSdk()
            initService()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                connectivityManager?.registerDefaultNetworkCallback(networkCallback)
            }
            initJPush()
        }

    }

    private fun initService() {
        if (!BuildConfig.SERVER_RELEASE) {
            if (AppStorage.serviceConfig != null) {
                ServerConfig.baseHost = AppStorage.serviceConfig!!.apiUrl
                ServerConfig.baseH5Host = AppStorage.serviceConfig!!.webUrl
                ServerConfig.baseIpH5Host = AppStorage.serviceConfig!!.ipWebUrl
                ServerConfig.baseCaewapH5Host = AppStorage.serviceConfig!!.caewapUrl
            }
        }
    }

    /**
     * 退出登录时候清除所有信息
     */
    private fun onLogout() {
        JPushHelper.deleteAlias()
        AppStorage.token = ""
        AppStorage.refreshToken = ""
        AppStorage.assetsToken = null
        UserStorage.user = null
    }

    companion object {
        private const val TAG: String = "ApplicationLog"
        lateinit var appContext: App
    }

    fun initSdk() {
        // mmkv
        MMKV.initialize(this)
        Toaster.init(this)
        Thread.setDefaultUncaughtExceptionHandler(GlobalExceptionHandler(this))
        Runnable {
            //腾讯x5
            QbSdk.unForceSysWebView()
            QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
                override fun onCoreInitFinished() {
                    LogUtils.e(TAG, "onCoreInitFinished")
                }

                override fun onViewInitFinished(b: Boolean) {
                    LogUtils.e(TAG, "onViewInitFinished")

                }
            })
            QbSdk.setDownloadWithoutWifi(true)

        }
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId,调试时将第三个参数设置为true
        CrashReport.initCrashReport(this, Constants.BUGLY_ID, BuildConfig.DEBUG)
        initBuglyData()

    }

    private fun initJPush() {
//        JCollectionAuth.setAuth(this, true)
        JPushInterface.setDebugMode(!BuildConfig.SERVER_RELEASE)
        JPushInterface.init(this)
        JPushHelper.setJPushAlias()
//        JPushInterface.getRegistrationID()
    }

    private fun initBuglyData() {
        if (AppStorage.token != null && AppStorage.token!!.isNotEmpty()) {
            CrashReport.setUserId(this, UserStorage.user?.phone ?: "")
            CrashReport.setUserSceneTag(this, UserStorage.user?.id ?: 0)
            CrashReport.putUserData(this, "token", AppStorage.token)
        }

    }

    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            ClassicsHeader(context)
        }

    }

    private val connectivityManager: ConnectivityManager? by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getSystemService(ConnectivityManager::class.java)
        } else {
            null
        }
    }
    private val networkCallback = object : ConnectivityManager.NetworkCallback() {

        override fun onAvailable(network: Network) {
            // 网络连接了
            // 可以在这里检查网络是否可以访问互联网
            val networkCapabilities = connectivityManager?.getNetworkCapabilities(network)
            if (networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) {
                // 网络可以访问互联网
                if (!netAvailable){
                    netAvailable = true
                    LiveEventBus.get<Boolean>(BusConstants.NET_EVENT).post(netAvailable)
                }

            } else {
                // 网络已连接，但无法访问互联网
                netAvailable = false
            }

        }

        override fun onLost(network: Network) {
            // 网络连接丢失
            netAvailable = false
        }

    }
}


